from subprocess import check_output
from hashlib import md5
from pathlib import Path
import shutil
import os

DST = '/a8root/gitlab-runner/nginx/html/android-pack'
APP = 'gmlivesdk'

BUILD = Path(__file__).parent.parent / "app" / "build" / "outputs"


def _md5(apk: str):
    s = md5()
    with open(apk, 'rb') as f:
        s.update(f.read())
    return s.hexdigest()


def _find_apk():
    from itertools import chain
    return chain(BUILD.glob('**/*sample-release.apk'),BUILD.glob('**/*aligned_signed.apk'))

def _find_mapping():
    from itertools import chain
    return chain(BUILD.glob('**/mapping.txt'))

def ding(robot: str, msg: str):
    print('-' * 80)
    print()
    print(robot)
    print(msg)
    print()
    print('-' * 80)

    import requests
    data = {
        "msgtype": "markdown",
        "markdown": {"title": "Build Apk", "text": msg}
    }
    print(requests.post(robot, json=data))

def get_cert(bundle_id,api_token):
    import requests
    data = {'type': 'android', 'bundle_id': bundle_id,'api_token': api_token}
    print(data)
    req = requests.post(url='http://api.fir.im/apps', data=data)
    cert_resp = req.content
    return cert_resp

def upload_fir(binary: str, path: str,version_name: str,version_code: str,changelog: str):
    import requests

    # 拿到相应的token
    cert_key = binary['key']
    print('cert_key:'+cert_key)

    cert_token = binary['token']

    cert_upload_url = binary['upload_url']
    print('upload_url:'+cert_upload_url)

    print('本地地址:'+path)
    # 要上传的文件
    file = {'file': ('ssvoice_'+version_code+'.apk', open(path, 'rb'))}     #显式的设置文件名

    param = {
        'key': cert_key,
        'token': cert_token,
        'x:name': '77爱玩',
        'x:version':version_name,
        'x:build': version_code,
        'x:changelog': changelog
    }
    requests.packages.urllib3.disable_warnings()
    req = requests.post(cert_upload_url,files=file, data=param, verify=False)
    content = req.content
    print(content)

def fir(apk_path: str,jid: str,email: str,version_name,version_code):
    import json
    api_token='3d1bfdd171a9439ea0c57e6ba222b4a0',
    bundle_id='com.gmlive.ssvoice',
    changelog=f'{"gitlab-ci提交-Job ID:"}{jid}{"-操作人:"}{email}'

    cert_json = json.loads(get_cert(bundle_id,api_token))
    binary_dirt = cert_json['cert']['binary']

    upload_fir(binary_dirt, apk_path,version_name,version_code,changelog)

def main(feature: str, robot: str, jid: str, email: str, is_upload_fir:int):
    DST_DIRE = f'{DST}/{APP}/{jid}'
    os.makedirs(DST_DIRE)
    url_root = f'http://10.224.32.16:10010/android-pack/{APP}/{jid}/'
    mapping = ''
    for mapping_file in _find_mapping():
        print ('for mapping address :',mapping_file)
        mapping = mapping_file
    print ('last mapping address :',mapping)
    for apk in _find_apk():
        print('apk: ', apk)
        sign = _md5(apk)
        size = os.path.getsize(apk) / 1024.0 / 1024.0
        dst_root = f'{feature}-{os.path.basename(os.path.dirname(os.path.dirname(apk)))}-{sign}'
        dst = f'{"apk"}-{dst_root}{".apk"}'
        shutil.copyfile(apk, os.path.join(DST_DIRE, dst))
        url = f'{url_root}{dst}'
        mapping_dst = f'{"mapping"}-{dst_root}{".txt"}'
        shutil.copyfile(mapping, os.path.join(DST_DIRE, mapping_dst))
        mapping_url = f'{url_root}{mapping_dst}'
        tip = "否" if is_upload_fir==0 else "是"
        msg = f'''\
## App: {APP}
### 分支: {feature}
### Job ID: [#{jid}](https://code.inke.cn/gz/android/ssvoice/-/jobs/{jid})
### 操作人: {email}
- [点我下载]({url})
- md5: {sign}
- size: {size:.2f}M
- mapping文件地址: {mapping_url}
- 下载地址: {url}
- 是否上传fir:{tip}
        '''
        ding(robot, msg)

        print('is_upload_fir:',is_upload_fir)

        if is_upload_fir == 1:

            #根据路径文件名截取版本号
            print(os.path.abspath(apk))
            s=os.path.abspath(apk).split('/')

            s1 = s[len(s)-1].split('_')
            print(str(s1))

            version_name=s1[0]
            print(version_name)
            version_code=s1[1]
            print(version_code)

            fir(os.path.join(DST_DIRE, dst),jid,email,version_name,version_code)
        else:
            print("不上传fir")

if __name__ == "__main__":
    import fire
    fire.Fire(main)
